package com.iwhalecloud.citybrain.flow.platform.manager.application.common.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.core.util.StrUtil;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.WebUtils;
import org.jasig.cas.client.validation.Assertion;

/**
 * @author lilh
 * @date 2021/4/7 12:27
 */
public class EmbedRequestFilter implements Filter {

    private String loginUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.loginUrl = filterConfig.getInitParameter("loginUrl");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(true);
        Assertion assertion = session != null ? (Assertion) session.getAttribute("_const_cas_assertion_") : null;
        String requestUrl = request.getRequestURL().toString();
        if (Objects.isNull(assertion)) {
            //未登录，则将请求地址加
            String embedRequestTag = "/embed/";
            if (requestUrl.contains(embedRequestTag)) {
                if (StrUtil.isNotBlank(request.getQueryString())) {
                    requestUrl = requestUrl + "?" + request.getQueryString();
                }
                if (Objects.nonNull(session)){
                    session.setAttribute(WebUtils.ORIGIN_EMBED_REQUEST_URL_PARAM, requestUrl);
                }
                response.sendRedirect(loginUrl);
                return;
            }
        } else {
            //已经登录了
            String embedRequestUrl = (String) session.getAttribute(WebUtils.ORIGIN_EMBED_REQUEST_URL_PARAM);
            if (StrUtil.isNotBlank(embedRequestUrl)) {
                session.removeAttribute(WebUtils.ORIGIN_EMBED_REQUEST_URL_PARAM);
                response.sendRedirect(embedRequestUrl);
                return;
            }
        }

        chain.doFilter(request, response);
    }
}
